//
//  HMLoginParam.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/9/20.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
/**
 *  封装用户登录参数，将参数保存到本地，以方便下次的自动登录，本类提供参数的保存，获取，判断票据是否过期等操作
 */
class HMLoginParam: TIMLoginParam {
    /**
     获取自身实例
     */
    static let share: HMLoginParam = {
        let _param = HMLoginParam()
        return _param
    }()
    
    
    
    public enum HMLPDoctorStatus: Int {
        case hm_Not        = -1
        case hm_Conduct    = 0
        case hm_Fail       = 1
        case hm_Success    = 2
    }
    /// 登录时间
    var tokenTime: NSInteger = 0
    /// 腾讯IM 签字
    var config: HMPlatformConfig?
    /// 腾讯IM appid
    let kSdkAppId: Int32 = 1400078014
    /// 生活模式
    var liveMode: Array<Any>?
    /// 运动情况
    var sportMode: Array<Any>?
    
    /// 获取当前用户信息 -- 该内容通过登陆，返回获取
    var user: Dictionary<String, Any> {
        get {
            if (UserDefaults.standard.string(forKey: "hm_user") != nil) {
                
                let str = UserDefaults.standard.string(forKey: "hm_user")
                let dic = self.getJSONStringToDictionary(JSONString: str)
                
                return  dic    //dictionary(forKey: "hm_user")!
            }else {
                 return Dictionary.init()
            }
        }
       
    }
    /// 获取当前用户信息 -- 通过接口获取
    var info: Dictionary<String, Any> {
        get {
            if (UserDefaults.standard.string(forKey: "hm_info") != nil) {
                
                let str = UserDefaults.standard.string(forKey: "hm_info")
                let dic = self.getJSONStringToDictionary(JSONString: str)
                
                return  dic
            }else {
                return Dictionary.init()
            }
        }
    }
    
    /// 医生审核状态 ，先判断 用户信息 内的 doctorStatus 状态是否完成医生
    /// -1 非医生, 0 审核中, 1 审核失败, 2 审核成功
    var isDoctorStatus: HMLPDoctorStatus = .hm_Not

    /// 获取当前用户性别  1- 男 ， 2- 女
    var sex: Int  {
        get {
            return HMLoginParam.share.user["sex"] as! Int
        }
    }
    /// 获取当前用户id
    var getCurrentId: String {
         get {
            return HMLoginParam.share.user["id"] as! String
         }
     }
    /// 获取当前用户头像
    var getCurrentImage: UIImage {
        get {
            if UserDefaults.standard.data(forKey: "currentImage") != nil {
                let _data = UserDefaults.standard.data(forKey: "currentImage")!
                let img = UIImage.init(data: _data)
                return img!
            }
            
            return UIImage.init(named: "logo")!
        }
        
//        set {
//            print("------>\(newValue)")
//
//        }
        
    }
    /// 获取当前用户昵称
    var getCurrentName: String? {
        get {
            return  UserDefaults.standard.string(forKey: "nick")
        }
    }
    

    /// IM 设置当前用户名称
    func im_setNickName(nick: String) {
       
        UserDefaults.standard.set(nick, forKey: "nick")
        TIMFriendshipManager.sharedInstance()?.setNickname(nick, succ: {
            print("设置nick成功")
        }, fail: { (code, err) in
            print("失败\(err)")
        })
    }
    /// IM 设置当前用户头像
    func im_setFaceUrl(urlStr: String) {
        
        // 保存一个UIImage
        let newUrl = configure.shareConfigure.IP_diagonal + urlStr
        UIImageView().img(url: newUrl) { (img) in
            let data = UIImagePNGRepresentation(img)
            UserDefaults.standard.set(data!, forKey: "currentImage")   //object(forKey: )
        }
        
        
        TIMFriendshipManager.sharedInstance()?.setFaceURL(urlStr, succ: {
             print("设置头像成功")
        }, fail: { (code, err) in
             print("失败\(err)")
        })
    }
    /// IM 设置当前用户性别
    func im_setGende(sex: Int) {
        // 0 - ， 1男 TIM_GENDER_MALE - 2女
        var gender: TIMGender
        if sex == 2 {
           gender = .GENDER_FEMALE
        }else if sex == 1 {
            gender = .GENDER_MALE
        }else {
           gender = .GENDER_UNKNOWN
        }

        TIMFriendshipManager.sharedInstance()?.setGender(gender, succ: {
            print("设置性别成功")
        }, fail: { (code, err) in
            print("失败\(err)")
        })
        
    }
    
     /// IM 设置当前用户自定义信息  custom 自定义属性（key为 NSString 类型，value为 NSData 或者 NSNumber 类型）
    func im_setCustom(dic: NSDictionary) {
        TIMFriendshipManager.sharedInstance()?.setCustom((dic as! [AnyHashable : Any]), succ: {
            print("成功回调，返回 TIMUserProfile 结构，包含用户资料=========>>>")
        }, fail: { (code, msg) in

        })
    
    }
    

     /// 更新当前用户登录信息 - 保存本地
     class func updateUser(_ dic: Dictionary<String, Any>) {
        HMLoginParam.share.im_setNickName(nick: dic["nickname"] as! String )
        HMLoginParam.share.im_setFaceUrl(urlStr: dic["iconUrl"] as! String)
        HMLoginParam.share.im_setGende(sex: dic["sex"] as! Int )
        let str = dic["phone"] as! String
        let phoneData = str.data(using: String.Encoding.utf8)
        HMLoginParam.share.im_setCustom(dic: ["phone": phoneData as Any])
        
        let  dicString = HMLoginParam.share.getJSONString(dic)
        UserDefaults.standard.set(dicString, forKey: "hm_user")
    }
    
    /// 更新当前用户体征信息
    /// 进入个人信息页自动更新接口内容 - 及保存本地
    class func updateInfo(_ dic: Dictionary<String, Any>) {
        let dicString = HMLoginParam.share.getJSONString(dic)
        UserDefaults.standard.set(dicString, forKey: "hm_info")
    }
    /// 登出清空数据
    class func wipeData() {
        if UserDefaults.standard.string(forKey: "hm_user") != nil {
             UserDefaults.standard.removeObject(forKey: "hm_user")  //清空 users 信息
        }
        if UserDefaults.standard.string(forKey: "hm_info") != nil {
           UserDefaults.standard.removeObject(forKey: "hm_info")
        }
       
        UserDefaults.standard.set(false, forKey: "hm_isLogin")
        
        if NetRequestTool.shareInstance.token != "" {
             NetRequestTool.shareInstance.token = "" //清空 token
        }
        
        // 退出成功 清空sig
        if UserDefaults.standard.string(forKey: "hm_sig") != nil {
            UserDefaults.standard.removeObject(forKey: "hm_sig")
        }
        
        
        HMPlatform.sharePlatform.logoutIMSDK {
            print("来了？？？")
        }
        
    }
    
}
